package com.tongzhou.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;



/**
 * 
 * 对memcached的操作
 * 
 */

public class SessionService
{
	private static SessionService instance = null;


	private String poolName = "cacheServer";

	private static MemcachedClient cachedClient = null; 
	
	private int expiryTime = 60;// minutes   session 失效时间

	private int getExpiryDate()
	{
		int time = expiryTime * 60;
		return time;
	}
	
	public static synchronized SessionService getInstance()
	{
		if (instance == null)
		{
			instance = new SessionService();
		}
		return instance;
	}

	/*private SessionService()
	{
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		InputStream input = cl.getResourceAsStream("sessionServer.properties");
		Properties props = new Properties();
		String serverlist = "127.0.0.1:18168";
		try
		{
			props.load(input);
			serverlist = props.getProperty("serverlist", "127.0.0.1:18168");
			poolName = props.getProperty("poolname", "sessionServer");
			input.close();

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		System.out.println("RemoteSession->serverlist="+serverlist);
		String[] servers = serverlist.split(",");
		
		pool = SockIOPool.getInstance(poolName);
		pool.setServers(servers);
		pool.setFailover(true);
		pool.setInitConn(10);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaintSleep(30);
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setAliveCheck(true);
		pool.initialize();
		
		SockIOPool pool = SockIOPool.getInstance(poolName);
		pool.setServers( servers );
		pool.setFailover( true );
		pool.setInitConn( 10 ); 
		pool.setMinConn( 5 );
		pool.setMaxConn( 250 );
		pool.setMaintSleep( 30 );
		pool.setNagle( false );
		pool.setSocketTO( 3000 );
		pool.setAliveCheck( true );
		pool.initialize();
		
		//初始化MemCachedClient
		if( cachedClient == null )
		{
			 cachedClient = new MemCachedClient( poolName );
		}
		
		cachedClient.setCompressEnable(false);
		cachedClient.setCompressThreshold(0);
	}*/
	
	
	private SessionService()
	{
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		InputStream input = cl.getResourceAsStream("cacheServer.properties");
		Properties props = new Properties();
		String serverhost = "127.0.0.1";
		String serverport = "11211";
		try
		{
			props.load(input);
			serverhost = props.getProperty("serverhost", "127.0.0.1");
			serverport = props.getProperty("serverport", "11211");
			expiryTime = Integer.valueOf(props.getProperty("expirytime", "60"));
			poolName = props.getProperty("poolname", "cacheServer");
			input.close();

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		System.out.println("RemoteSession->serverlist="+serverhost+":"+serverport);
		
		try {
			cachedClient =new XMemcachedClient(serverhost,Integer.valueOf(serverport));
		} catch (IOException e1) {
			e1.printStackTrace();
		} 
	}
	
	
	
	
	

	public boolean sessionExists(String id)
	{
		MemcachedClient mc = this.getMemCachedClient();
		try {
			if(mc.get(id)==null){
				return false;
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		return true;
	}

	
	public Map getSession(String sessionId)
	{
		MemcachedClient mc = this.getMemCachedClient();

		Map session = null ;
		try {
			try{
				session = (Map) mc.get(sessionId);  //根据ID获取当前session
			}catch(Exception e){
				e.printStackTrace();
			}
			if (session == null)   //如果当前session 不存在， 则创建一个新的session 并设定有效期
			{
				session = new HashMap(5);
				mc.set(sessionId , getExpiryDate() , session);
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return session;
	}
	
	public Map getSession(String sessionId, boolean create)
	{
		MemcachedClient mc = this.getMemCachedClient();

		Map session = null;
		try {
			try{
				session = (Map) mc.get(sessionId);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			if (session == null)
			{
				if (create)
				{
					session = new HashMap(5);
					mc.set(sessionId , getExpiryDate()  , session);
					System.out.println("Create Seesion default expity date:"+getExpiryDate());
				}
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return session;
	}

	/**
	 * 创建一个session
	 * @param id
	 * @param create
	 * @param expiryTime 过期时间(秒)
	 * @return
	 */
	public Map getSession(String sessionId, boolean create, int expiryTime)
	{
		long t1 = System.currentTimeMillis();
		
		MemcachedClient mc = this.getMemCachedClient();

		Map session = null ;
		try {
			try{
				session = (Map) mc.get(sessionId);
			}catch(Exception e){
				e.printStackTrace();
			}
			if (session == null)
			{
				if (create)
				{
					session = new HashMap(5);
					System.out.println("Create Seesion expity date:"+expiryTime);
					mc.set(sessionId , expiryTime  , session);
				}
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		return session;
	}
	
	public void saveSession(String sessionId, Map session)
	{
		MemcachedClient mc = this.getMemCachedClient();
		
		try {
			mc.set(sessionId, getExpiryDate(), session);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		
	}
	
	public void saveNoExpirySession(String sessionId, Map session)
	{
		MemcachedClient mc = this.getMemCachedClient();
		
		try {
			mc.set(sessionId , 0  , session);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 保存session
	 * @param id
	 * @param session
	 * @param expiryTime 过期时间（单位秒)
	 */
	public void saveSession(String sessionId, Map session, int expiryTime)
	{
		MemcachedClient mc = this.getMemCachedClient();
		try {
			mc.set(sessionId, expiryTime , session);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
	}

	public void removeSession(String sessionId)
	{
		MemcachedClient mc = this.getMemCachedClient();
		try {
			mc.delete(sessionId);
			System.out.println("=============removeSession======id="+sessionId);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		
	}

	public void updateExpiryDate(String sessionId)
	{
		MemcachedClient mc = this.getMemCachedClient();
		Map session = null;
		try {
			try{
				session = (Map) mc.get(sessionId);
			}catch(Exception e){
				e.printStackTrace();
			}
			if (session != null)
			{
				mc.replace(sessionId, getExpiryDate() , session);
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
		
	}

	private MemcachedClient getMemCachedClient()
	{
		return cachedClient;
	}

	protected void finalize()
	{
		if (this.cachedClient != null)
		{
			try {
				this.cachedClient.shutdown();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String agr[]) throws IOException, TimeoutException, InterruptedException, MemcachedException
	{
//		MemcachedClient client=new XMemcachedClient("192.168.0.168",11211); 
//		HashMap map = new HashMap();
//		map.put("111", "i am 1111");
//		//同步存储value到memcached 
//		//90 * 24 * 60 * 60
//		client.set("key", 1,map); 
////		Thread.sleep(400);
//		//从memcached获取key对应的value 
//		//Object someObject=client.get("key"); 
////		 Thread.sleep(1000);
//		//从memcached获取key对应的value,操作超时2秒 
//		map=client.get("key", 2000); 
//		System.out.println("is:"+ map.get("111"));
//		Thread.sleep(1000);
		/*//从memcached获取key对应的value,操作超时2秒 
		map=client.get("key",2000); 
		System.out.println("is:"+ map.get("111"));
		Thread.sleep(1000);
		//从memcached获取key对应的value,操作超时2秒 
		map=client.get("key",2000); 
		System.out.println("is:"+ map.get("111"));
		
		//删除value 
		client.delete("key");*/
		System.out.println("======================abcdedf");
//		SessionUtil.invalidate(SessionUtil.createSessionId("123", "glg@163.com"));
		System.exit(0);
	}
}
